package lesson6;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    DatagramSocket socket = null;
    String serverIp;
    int serverPort;

    public UdpClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动==");
        while(true){
            //1 在控制台输入请求
            Scanner scanner = new Scanner(System.in);
            System.out.print("->");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2 构造请求发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //3 接受服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //4 在控制台打印响应
            System.out.println(response);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient server = new UdpClient("127.0.0.1", 9090);
        server.start();
    }
}
